package com.babo72.android_test;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class DrawableFromURL extends Activity {
	
	//private static final String IMG_URL = "http://img.naver.net/static/newsstand/up/2012/1119/nsd101424267.gif";
	private static final String IMG_URL = "https://stickergw.joyn.olleh.com/repository/sticker/187/1/kt_187_1_xhdpi.png";
	private View changeView;
	private Context context;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this.getApplicationContext();
		
		setContentView(R.layout.drawable_from_url);
		
		Button btn = (Button) this.findViewById(R.id.btnLoad);
		changeView = this.findViewById(R.id.vImage);
		
		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d("TAG", "loading image...");
				LoadImage loadImage = new LoadImage(changeView);
				loadImage.execute(IMG_URL);
			}
		});
	}
	
	public class LoadImage extends AsyncTask<String, Void, Drawable> {
		
		private View view;

		public LoadImage(View v) {
			view = v;
		}
		
		@Override
		protected Drawable doInBackground(String... strs) {
			try {
				Drawable drawable = drawableFromUrl(strs[0]);
				return drawable;
			} catch(IOException e) {
				Log.e("TAG", "error", e);
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Drawable result) {
			view.setBackground(result);
		}

		public Drawable drawableFromUrl(String url) throws IOException {
			HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
			connection.connect();
			InputStream input = connection.getInputStream();

			Bitmap x = BitmapFactory.decodeStream(input);
			return new BitmapDrawable(context.getResources(), x);
		}	
	}
}
